// 调用合约方法approve
$('#btnApprove').click(function(){
	var addr = $('#approveAddr').val() || '';
	var val = $('#approveVal').val() || '';
	var key = $('#approveKey').val() || '';

	checkNull(addr, val, key);
	
	if (key.indexOf('0x') !== 0) {
			key = '0x' + key;
	}

	var account = getAccount(key);

	val = web3.utils.toWei(val, 'ether');

	var funcAbi = token.methods.approve(addr, val).encodeABI();
	
	var txData = {
			gasLimit: web3.utils.toHex(100000),
      from: account.address,
      to: vccAddr,
      value: '0x00',
      data: funcAbi
  }
  sendTransaction(txData, key, '#approveRes');
});

// 不使用默认账户进行转token
$('#btnOtherToken').click(function(){
	var fromAddr = $('#fromAddrOtherToken').val() || '';
	var fromKey = $('#fromAddrOtherKeyToken').val();
	var toAddr = $('#toAddrOtherToken').val() || '';
	var num = $('#toValOtherToken').val() || '';

	checkNull(fromAddr, toAddr, num, fromKey);

	if (fromKey.indexOf('0x') !== 0) {
		fromKey = '0x' + fromKey;
	}

	var data = token.methods.transferFrom(fromAddr, toAddr, num).encodeABI();
	var txData = getTxData(fromAddr, toAddr, data, '0x00');
	sendTransaction(txData, fromKey, '#transOtherToken');
});

// 不使用默认地址进行eth转账
$('#btnOtherEth').click(function(){
	var fromAddr = $('#fromAddrEth').val() || '';
	var fromAddrKey = $('#fromAddrKey').val() || '';
	var toAddr = $('#toAddrEth').val() || '';
	var num = $('#toValEth').val() || '';
	
	if (fromAddr === '' || toAddr === '' || num === '' || fromAddrKey === ''){
		alert('请输入正确的参数');
		return;
	}
	var res = web3.eth.accounts.signTransaction({
		gasLimit: web3.utils.toHex(100000),
		from: fromAddr,
		to: toAddr,
		value: web3.utils.toWei(num, 'ether')
	}, fromAddrKey).then(tx => {
		console.log("Result: ", tx);
		
		web3.eth.sendSignedTransaction(tx.rawTransaction).on('receipt', function(res){
			console.log(res);
			$('#transOtherEth').html('操作结果：' + JSON.stringify(res));
		});
	});
	
});


// token转账
$('#btnTransToken').click(function(){
		var addr = $('#toAddrToken').val() || '';
		var num = $('#toValToken').val() || '';
		var key = $('#tokeyToken').val() || '';

		checkNull(addr, num, key);
		
		if (key.indexOf('0x') != 0) {
			key = '0x' + key;
		}
		
		var funcAbi = token.methods.transfer(addr, web3.utils.toWei(num, 'ether')).encodeABI();
	
//	console.log(`encodeABI: ${funcAbi}`);
//	var funcAbi2 = '0xa9059cbb' + addPreZero(web3.utils.toHex(addr).substr(2)) + addPreZero(web3.utils.toHex(num).substr(2));
//	console.log(`encodeABI2: ${funcAbi2}`);
	
		var txData = {
				gasLimit: web3.utils.toHex(100000),
	      from: web3.eth.defaultAccount,
	      gasPrice: web3.utils.toWei('10', 'gwei'),
	      to: vccAddr,
	      data: funcAbi,
	      value: '0x00'
	  }
	
		sendTransaction(txData, key, '#transTokenRes');
});


token.methods.balanceOf(vccAddr).call().then(console.log);


// 编译合约
$('#compile').click(function(){
	var code = $('#contractSource').val() || '';
	if (code === '') {
		alert('参数不能为空');
		return;
	}
//	web3.eth.getCompilers().then(rs => {
//		$('#compileInfo').html(JSON.stringify(rs));
//		console.log(rs);
//	}).cache(err => {
//		console.log(err);
//	});
	web3.eth.compile.solidity(code).then(res => {
		console.log(res);
	});
})

// 部署简单合约
$('#deploy').click(function(){
	var code = $('#sourceCode').val() || '';
	var abi = $('#sourceAbi').val() || '';
	var args = $('#deployArgs').val();
	if (code === '' || abi === '' || args === ''){
		alert('参数不能为空');
		return;
	}
	
	if (code.indexOf('0x') != 0) {
		code = '0x' + code;
	}
	
	var constract = new web3.eth.Contract(JSON.parse(abi));

	console.log(eval('(' + args + ')'));

	var transaction = constract.deploy({data: code, arguments: eval('(' + args + ')')})
	
	var options = {
		data: transaction.encodeABI(),
		gas: 4000000,
		gasPrice: web3.utils.toWei('10', 'gwei')
	}
	
	web3.eth.accounts.signTransaction(options, '0x' + DEFAULT_ACCOUNT_KEY).then(tx => {
		console.log('Result: ', tx);
		
		web3.eth.sendSignedTransaction(tx.rawTransaction).on('receipt', function(res){
			console.log(JSON.stringify(res));
		})
	})
})

//$('#btnContractAddr').click(function(){
//	var addr = $('#contractAddr').val() || '';
//	if (addr === '') {
//		alert('请输入合约地址');
//		return;
//	}
//	var token = new web3.eth.Contract(null, '0xE5F28B45908E8B8A34689305c29adC79997653C0');
//	console.log(JSON.stringify(token));
//})

// 获得pending状态的block
$('#pending').click(function(){
	web3.eth.getBlock('pending', function(err, block){
		if (err){
			$('#pendingInfo').html(err);
		} else {
			$('#pendingInfo').html(JSON.stringify(block));
		}
	})
});

// 转账eth
$('#btnTransEth').click(function(){
		var addr = $('#toAddr').val() || '';
		var num = $('#toVal').val();
		var key = $('#toKey').val();

		checkNull(addr, num, key);

		var account = getAccount(key);

		var txData = {
			  from: web3.eth.defaultAccount,
				to: addr,
				value: web3.utils.toWei(num, 'ether'),
				data: '0x00',
				gasLimit: web3.utils.toHex(200000),
				gasPrice: '10000000000'
		}

		sendTransaction(txData, account.privateKey, '#transEthRes');
});

// 查询账户
$('#btnQuery').click(function(){
	$('#queryInfo').html('查询结果：');
	var addr = $('#queryAccount').val() || '';
	if ('' === addr){
		alert('请输入地址');
		return;
	}
	
	web3.eth.getBalance(addr).then(function(res){
		$('#queryInfo').html($('#queryInfo').html() + ",eth: " + web3.utils.fromWei(res, 'ether'));
	});
	
	token.methods.balanceOf(addr).call().then(res => {
		$('#queryInfo').html($('#queryInfo').html() + ', vcc: ' + web3.utils.fromWei(res, 'ether'));
	});
})

// 创建账户
$("#newBtn").click(function(){
	$('#newAddress').html('');
	var pwd = $('#newAccount').val();
	var account = web3.eth.accounts.create();
	if (pwd === ''){
		$('#newAddress').html(JSON.stringify(account));
	} else {
		var res = web3.eth.accounts.encrypt(account.privateKey, pwd);
		$('#newAddress').html('账户信息： ' + JSON.stringify(account) + ' , 钱包信息： ' + JSON.stringify(res));		
	}
});

// 导出钱包
$('#btnWalletOutput').click(function(){
	$('#walletOutputInfo').html('');
	var key = $('#walletOutput').val() || '';
	var pwd = $('#walletPwd').val() || '';
	if (key === '' || pwd === ''){
		alert('私钥不能为空');
		return;
	}
	var res = web3.eth.accounts.encrypt(key, pwd);
	$('#walletOutputInfo').html(JSON.stringify(res));
});

// 导入钱包
$('#btnWalletInput').click(function(){
	$('#walletInputInfo').html('');
	var tt = $('#walletInput').val() || '';
	var key = $('#walletInPwd').val() || '';
	if (tt === '' || key === ''){
		alert('关键数据不能为空');
		return;
	}
	var tob = JSON.parse(tt);
	var res = web3.eth.accounts.decrypt(tob, key);
	$('#walletInputInfo').html(JSON.stringify(res));
});

// 监控合约方法下拉框变化
$('#contractFunc').change(function(){
	var ss = $(this).children('option:selected');
	var name = ss.val();
	var inputLen = ss.attr('data-inputs-length');
	var inputArgsName = ss.attr('data-inputs-args-name');
	var inputArgsType = ss.attr('data-inputs-args-type');
	var constant = ss.attr('data-constant');
	if (constant == "true") {
		$('#query').show();
		$('#invoke').hide();
	} else {
		$('#query').hide();
		$('#invoke').show();
	}
	
	console.log(`name: ${name}, 参数长度: ${inputLen}, 参数名称: ${inputArgsName}, 参数类型: ${inputArgsType}`);
	
	// 获得父元素的父元素，准备拼接
	var $body = $(this).parent().parent();
	console.log($body.children());
	for (var i=0, l=$body.children().length - 1; i<l; i++) {
		$body.children().get(1).remove();
	}
	$body.append(formGroup(inputLen, inputArgsName.split(','), inputArgsType.split(',')));
});


$('#btnQuery2').click(function(event) {
	var addr = $('#queryAccount2').val();
	if (addr.indexOf('0x') === 0) {
		addr = addr.substring(2);
	}

	web3.eth.call({
		to: vccAddr,
		data: '0x70a08231' + addPreZero(addr)
	}).then(res => {
		console.log(res);
		var result = web3.utils.fromWei(web3.utils.hexToNumberString(res), 'ether');
		console.log(result);

	})

});

// 查询类别操作
$('#query').click(function(){
	$(this).parent().parent().parent().children('p').remove();
	
	var ss = $('#contractFunc').children('option:selected');
	var inputLen = ss.attr('data-inputs-length');
	var inputArgsName = ss.attr('data-inputs-args-name');
	var inputArgsType = ss.attr('data-inputs-args-type');
	var signature = ss.attr('data-signature');
	var outType = ss.attr('data-output-type');
	
	console.log(signature);
	var attrs = signature;
	if (inputLen != 0) {
		$('input[name=inputs]').each(function(index, dom){
			attrs += addPreZero(web3.utils.toHex($(dom).val()).substring(2));
		});
	}
	
	console.log(attrs);

	web3.eth.call({
		to: vccAddr,
		data: attrs
	}).then(rs => {
		var res = '';
		if (outType === 'string') {
//			console.log(web3.utils.hexToUtf8(rs).replace(/[^a-z]+/ig, ''));
			res = web3.utils.hexToUtf8(rs).replace(/[^a-z]+/ig, '')
		} else if (outType === 'uint8') {
			console.log(web3.utils.hexToNumber(rs));
			res = web3.utils.hexToNumber(rs);
		} else if (outType === 'uint256') {
			console.log(web3.utils.fromWei(web3.utils.hexToNumberString(rs), 'ether'));
			res = web3.utils.fromWei(web3.utils.hexToNumberString(rs), 'ether');
		}
		$(this).parent().parent().parent().append(info(`result hex: ${rs}, \n result decode: ${res}`));
	}).catch(err => {
		console.error(err);
		$(this).parent().parent().parent().append(errs(`result err: ${err}`));
	});
	
});

// 执行调用
$('#invoke').click(function(){
	var that = this;
	$(this).parent().parent().parent().children('p').remove();
	
	var ss = $('#contractFunc').children('option:selected');
	var inputLen = ss.attr('data-inputs-length');
	var inputArgsName = ss.attr('data-inputs-args-name');
	var inputArgsType = ss.attr('data-inputs-args-type');
	var signature = ss.attr('data-signature');
	var outType = ss.attr('data-output-type');
	
	var attrs = signature;
	var fromAddr = '';
	
	var flag = false;
	if (inputLen != 0) {
		$('input[name=inputs]').each(function(index, dom){
			var $dom = $(dom);
			var type = $dom.attr('data-type');
			var value = $dom.val();
			if ($dom.attr('data-isfrom') !== 'true') {
				if ($dom.val() === '') {
					flag = true;
				} else if (type === 'address') {
					if (!web3.utils.isAddress(value)) flag = true;
				}
				attrs += addPreZero(web3.utils.toHex(value).substring(2));
			} else {
				fromAddr = $dom.val();
			}
		});
	}
	
	console.log(signature);
	console.log(attrs);
	if (flag) {
		layer.msg('参数异常');
		return;
	}
	
	var txData = {
			gasLimit: web3.utils.toHex(100000),
      from: web3.eth.defaultAccount,
      to: vccAddr,
      data: attrs
  }
	
	if (fromAddr !== '') {
		txData.from = fromAddr;
	}
	
	layer.prompt({
		title: '请输入您的密码',
		formType: 1
	}, function(pass, index){
		console.log(pass);
		if (pass.indexOf('0x') != 0) {
			pass = '0x' + pass;
		}
		web3.eth.accounts.signTransaction(txData, pass).then(function(tx){
			console.log("Result: ", tx);
			
			var ld = layer.load(0, {
				shade: [0.4, '#fff']
			});
			
			web3.eth.sendSignedTransaction(tx.rawTransaction).on('receipt', function(res){
				layer.close(ld);
				layer.msg('操作结果：' + JSON.stringify(res));
				$(that).parent().parent().parent().append(info('操作结果：' + JSON.stringify(res)));
			}).on('error', err => {
				layer.close(ld);
				$(that).parent().parent().parent().append(errs('操作结果：' + JSON.stringify(err)));
			});
		});
		layer.close(index);
	});
	
	
});

// 设置代币价格
$('#btnPrice').click(function(event) {
	var key = $('#priceKey').val();
	var buyValue = $('#priceBuyValue').val();
	var sellValue = $('#priceSellValue').val();

	checkNull(key, buyValue, sellValue);

  // var buy = web3.utils.toWei(buyValue, 'ether');
  // var sell = web3.utils.toWei(sellValue, 'ether');

	var account = getAccount(key);

	var data = token.methods.setPrices(sellValue, buyValue).encodeABI();

	var txData = getTxData(account.address, vccAddr, data, '0x00');
	sendTransaction(txData, account.privateKey, '#priceRes');
});

// 出售代币
$('#btnSellToken').click(function(event) {
		var key = $('#sellTokenKey').val();
		var value = $('#sellTokenValue').val();

		checkNull(key, value);

		var account = getAccount(key);

		var data = token.methods.sell(web3.utils.toWei(value, 'ether')).encodeABI();

		var txData = getTxData(account.address, vccAddr, data, '0x00');
		sendTransaction(txData, account.privateKey, '#sellRes');
});

// 购买vcc
$('#btnBuyToken').click(function(event) {
	var value = $('#buyTokenValue').val();
	var key = $('#buyTokenKey').val();

	checkNull(key, value);

	var account = getAccount(key);

	var data = token.methods.buy().encodeABI();
	var txData = getTxData(account.address, vccAddr, data, web3.utils.toWei(value, 'wei'));
	sendTransaction(txData, account.privateKey, '#buyTokenRes');
});

// 销售合约：设置价格
$('#btnSellPrice').click(function(event) {
		var key = $('#sellSetPriceKey').val();
		var buyPrice = $('#sellBuyPrice').val();
		var sellPrice = $('#sellSellPrice').val();

		checkNull(key, buyPrice, sellPrice);

		var account = getAccount(key);

		var data = sellContract3.methods.setPrice(buyPrice, sellPrice).encodeABI();

		var txData = getTxData(account.address, sellAddr3, data, '0x00');
		sendTransaction(txData, account.privateKey, '#sellSetPriceRes');
});

// 销售合约：购买代币
$('#btnSellBuyVcc').click(function(event) {
		var key = $('#sellBuyVccKey').val();
		var value = $('#sellBuyVccValue').val();

		checkNull(key, value);

		value = web3.utils.toWei(value, 'ether');

		var account = getAccount(key);

		var data = sellContract3.methods.buy().encodeABI();

		var txData = getTxData(account.address, sellAddr3, data, web3.utils.toWei(value, 'wei'));

		sendTransaction(txData, account.privateKey, '#sellBuyVccRes');
});

// 出售代币
$('#btnSellSellVcc').click(function(event) {
		var key = $('#sellSellVccKey').val();
		var value = $('#sellSellVccNum').val();

		checkNull(key, value);

		value = web3.utils.toWei(value, 'ether');

		var account = getAccount(key);
		var extraData = web3.utils.utf8ToHex('测试销售');
		console.log(extraData);
		var data = sellContract3.methods.sell(value).encodeABI();

		var txData = getTxData(account.address, sellAddr3, data, '0x00');
		sendTransaction(txData, account.privateKey, '#sellSellVccRes');
});

// 从合约中提取eth
$('#btnExtract').click(function(){
		var key = $('#extractKey').val();
		var num = $('#extractNum').val();

		checkNull(key, num);

		var account = getAccount(key);

		var data = sellContract3.methods.extract(web3.utils.toWei(num, 'ether')).encodeABI();

		var txData = getTxData(account.address, sellAddr3, data, '0x00');
		sendTransaction(txData, account.privateKey, '#extractRes');
});

// 从合约中提取代币
$('#btnExtractToken').click(() => {
		var key = $('#extractTokenKey').val();
		var num = $('#extractTokenNum').val();
		checkNull(key, num);
		var account = getAccount(key);
		var data = sellContract3.methods.extractToken(web3.utils.toWei(num, 'ether')).encodeABI();
		var txData = getTxData(account.address, sellAddr3, data, '0x00');
		sendTransaction(txData, account.privateKey, '#extractTokenRes');
});

// 暂停合约
$('#btnSellStop').click(() => {
		var key = $('#sellStopKey').val();
		checkNull(key);
		var account = getAccount(key);
		var data = sellContract3.methods.stop().encodeABI();
		var txData = getTxData(account.address, sellAddr3, data, '0x00');
		sendTransaction(txData, account.privateKey, '#sellStopRes');
});

// 开始合约
$('#btnSellStart').click(() => {
	  var key = $('#sellStartKey').val();
	  checkNull(key);
	  var account = getAccount(key);
	  var data = sellContract3.methods.start().encodeABI();
	  var txData = getTxData(account.address, sellAddr3, data, '0x00');
	  sendTransaction(txData, account.privateKey, '#sellStartRes');
});

// 删除合约
$('#btnSellClear').click(function(event) {
	  var key = $('#sellClearKey').val();
	  checkNull(key);
	  var account = getAccount(key);
	  layer.msg('目前禁止操作');
	  return;
	  var data = sellContract3.methods.clear().encodeABI();
	  var txData = getTxData(account.address, sellAddr3, data, '0x00');
	  sendTransaction(txData, account.privateKey, '#sellClearRes');
})

// 测试离线签名
$('#testOffSign').click(function() {
		var account = getAccount('37e1d425914bea238a4e3ea744a0969951d82ab714e5e6f43da40199a1320db7');
		console.log(account);

		var txData = getTxData(account.address, '0x4e13A733826cB2146735534d8e56602384655393', web3.utils.toWei('0.01', 'ether'), web3.utils.toWei('1', 'ether'));

		var tx = new ethereumjs.Tx(null, 4);
		console.log(web3.utils.hexToNumber(web3.utils.toWei('10', 'gwei')));
		web3.eth.getTransactionCount(web3.eth.defaultAccount).then(res => {
				tx.nonce = res;
				tx.gasPrice = web3.utils.hexToNumber(web3.utils.toWei('10', 'gwei'));
				tx.gasLimit = 100000;

				tx.value = '0x' + (new web3.utils.BN(web3.utils.toWei('0.01', 'ether'))).toString('hex');
				// tx.data = '';
				// tx.from = '0x1aC2F04ea466991bC91C802150a1D2730D2bBB65';
				tx.to = '0x4e13A733826cB2146735534d8e56602384655393';

				// console.log(tx.getSenderAddress().toString('hex'));
				console.log('0x' + (new web3.utils.BN(web3.utils.toWei('0.01', 'ether'))).toString('hex'));
				console.log(JSON.stringify(tx));

				var pri = ethereumjs.Buffer.Buffer.from(DEFAULT_ACCOUNT_KEY, 'hex');
				console.log(pri);
				tx.sign(pri);
				console.log(tx.serialize().toString('hex'));

				web3.eth.sendSignedTransaction('0x' + tx.serialize().toString('hex')).on('receipt', res => {
						layer.msg('操作成功');
						console.log(res);
				}).on('error', err => {
						layer.msg('操作异常');
						console.log(err);
				});
		});

		

});

$('#airSub').click(function(event) {
		var key = $('#airKey').val();
		var contract = $('#airContractAddr').val();
		var num = $('#airNumber').val();
		var receipt = $('#airAddrs').val();
		checkNull(key, contract, num, receipt);

		var account = getAccount(key);

		if (receipt.indexOf('[') != 0 || receipt.indexOf(']') != (receipt.length - 1)) {
				layer.alert('参数格式错误');
				return false;
		}

		var _recipients = eval('(' + receipt + ')');
		if (_recipients.length == 0) {
				layer.alert('空投地址不能为空');
				return false;
		}

		var funcAbi = air.methods.batchTransfer(contract, _recipients, web3.utils.toWei(num, 'ether')).encodeABI();



		// var txData = getTxData(account.address, airAddr, funcAbi, '0x00');

		web3.eth.estimateGas({
				from: account.address,
				to: airAddr,
				data: funcAbi
		}).then(limit => {
				web3.eth.accounts.signTransaction({
						from: account.address,
						to: airAddr,
						value: '0x00',
						data: funcAbi,
						gasLimit: limit,
						gasPrice: web3.utils.toWei('10', 'gwei')
				}, account.privateKey).then(result => {
						console.log(result);
						web3.eth.sendSignedTransaction(result.rawTransaction).on('receipt', receipt => {
								console.log(receipt);
								$('#airRes').html(JSON.stringify(receipt));
						}).on('error', err => {
								console.log(err);
								layer.alert(err);
						});;
				})
		})

		// sendTransaction(txData, account.privateKey, '#airRes');
});




$('#btnQueryETHHis').click(function(){
		var addr = $('#queryETHHisAddr').val();
		checkNull(addr);

		$('#queryETHHisRes').html('');

		web3.eth.getBlockNumber().then(num => {
				$.getJSON(APIURL, getTxListParam(addr, num, 1), function(json, textStatus) {
						if (json.status === '1') {
								var html = '';
								json.result.forEach(tx => {
										if (tx.value !== '0') {
												html += `to：${tx.to}，value：${web3.utils.fromWei(tx.value, 'ether')} ETH ，timestamp：${new Date(tx.timeStamp * 1000).toLocaleString()}\n<br>`;
										}
								});
								$('#queryETHHisRes').html(html);
						} else {
							  $('#queryETHHisRes').html('查询异常');
						}
						// console.log(json);					// jsonObj
						// console.log(textStatus);		// success
				});
		});

})

$('#btnQueryVccHis').click(function(event) {
		var addr = $('#queryVccHisAddr').val();
		checkNull(addr);

		$('#queryVccHisRes').html('');

		$.getJSON(APIURL, getTokenTxListParam(vccAddr, addr, 1), function(json, textStatus) {
				if (json.status === '1') {
						var html = '';
						json.result.forEach(tx => {
								html += `to：${tx.to}，value：${web3.utils.fromWei(tx.value, 'ether')} ${tx.tokenSymbol}，timestamp：${new Date(tx.timeStamp * 1000).toLocaleString()}\n<br>`;
						})
						$('#queryVccHisRes').html(html);
				} else {
						$('#queryVccHisRes').html('查询异常');
				}
		});

});



